<template>
	<div class="shop-cart">
		<Nav></Nav>
		<Header></Header>
		<div class="goods">
			<div class="goods-num">
				全部商品&nbsp;&nbsp;{{ cartData.total_goods_number }}
			</div>
			<table>
				<tr>
					<th>
						<input type="checkbox" :checked="allChecked" @click="cheakedAll">
						全选
					</th>
					<th>商品</th>
					<th></th>
					<th>单价</th>
					<th>数量</th>
					<th>小计</th>
					<th>操作</th>
				</tr>
				<tr v-for="(item,key) in cartItemData"
				:key="key">
					<td>
						<input type="checkbox" 
						:checked="item.checked" 
						@click="changeChecked(item.good.good_id)">
					</td>
					<td>
						<img :src="item.good.photo_URL" alt="" />
					</td>
					<td>{{ item.good.name }}</td>
					<td>￥{{ item.good.price }}</td>
					<td>
						<el-input-number
						v-model="item.num"
						@change="(newValue,oldValue)=>handleChange(newValue,oldValue,item.good.good_id,newValue>oldValue?'add':'remove')"
						:min="1"
						:max="10"
						label="描述文字"></el-input-number>
					</td>
					<td>￥{{ (item.good.price*item.num).toFixed(2) }}</td>
					<td>删除</td>
				</tr>
			</table>
			<div class="bottom-tool">
				<div class="tool-left">
					<input type="checkbox"  :checked="allChecked" @click="cheakedAll">
					全选
					<span class="delete-seleted">
						删除选中商品
					</span>
					<span class="clear-cart">
						清理购物车
					</span>	
				</div>
				<div class="tool-right">
					<span class="seleted-goods">已选择商品<em>{{ seletedGoodsCount }}</em>件商品</span>
					<span class="price-count">总价：<em>￥{{ priceCount }}</em></span>
					<a class="go-order" @click="goOrder">去结算</a>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from "vue";
import Nav from "@/components/common/Nav";
import Header from "@/components/home/Header";
import { getCartDatilData,updateCartGoodsNum } from "@/network/cart";
import { createOrderData } from "@/network/order.js"
import { useRouter } from "vue-router";
import { useStore } from "vuex";
const store = useStore()
const router = useRouter();

let cartData = ref({})  // 购物车详情
let cartItemData = ref([])  // 购物车项详情
let cartId = ref(1)

onMounted(()=>{
	// 验证用户的登陆状态
	getCartDatilData().then(res=>{
		cartItemData.value = res.data.cart_items;
		cartData.value = res.data.cart;
		console.log(cartData.value)
		console.log(cartItemData.value)
	}).catch(err=>{
		console.log(err)
	})
})
 
const handleChange = (newValue,oldValue,goodId,action) => {
	console.log(newValue,oldValue,goodId,action);
	const data = ref({
		"user_id": 1,
	 	"good_id":goodId,
	 	"num": 1,
	 	"action":action,
	});
	updateCartGoodsNum(data.value).then(res=>{
		console.log(res)
	}).catch(err=>{
		console.log(err)
	})
}

const allChecked = ref(false);
const seletedGoodsCount = ref(0);
const priceCount = ref(0);
const cheakedAll = () => {
  if (allChecked.value) {
    cartItemData.value.forEach(item => item.checked = false);
	seletedGoodsCount.value = 0;
  } else {
    cartItemData.value.forEach(item => item.checked = true);
	seletedGoodsCount.value = cartItemData.value.length;
  }
  allChecked.value = !allChecked.value;
};

const changeChecked = (good_id) => {
  const item = cartItemData.value.find(item => item.good.good_id === good_id);
  if (item) {
    item.checked = !item.checked;
    updateSelectionCountAndPrice();
  }
};

const updateSelectionCountAndPrice = () => {
  let newSeletedGoodsCount = 0;
  let newPriceCount = 0;
  cartItemData.value.forEach(item => {
    if (item.checked) {
      newSeletedGoodsCount += 1;
      newPriceCount += item.good.price * item.num;
    }
  });
  seletedGoodsCount.value = newSeletedGoodsCount;
  priceCount.value = newPriceCount.toFixed(2);
  allChecked.value = newSeletedGoodsCount === cartItemData.value.length;
};

watch(() => cartItemData.value, (newValue, oldValue) => {
  updateSelectionCountAndPrice();
	}, {
  deep: true,
});


// 去结算，实现创建订单功能
let orderGoodsList=ref([])
const goOrder=()=>{
	for(let i in cartItemData.value){
		if(cartItemData.value[i].checked==true){
			orderGoodsList.value.push(cartItemData.value[i])
		}
	}
	console.log(orderGoodsList.value)
	alert(orderGoodsList.value)
	
	let orderData=reactive({
		trade:{
			total_price:priceCount.value,
		},
		good:orderGoodsList.value,
	})
	//往后端发请求
	let orderNo = ref('');
	console.log(orderData)
	createOrderData(orderData).then(res=>{
		// console.log(res.data)
		orderNo.value = res.data.trade_no;
		router.push('/order/'+ orderNo.value);
		store.dispatch('updateCart');
	})
}
</script>

<style lang="less" scoped>
	.shop-cart{
		.goods{
			width: var(--content-width);
			margin: 0 auto;
			.goods-num{
				color: #e2231a;
				font-size: 16px;
				font-weight: 700;
			}
			table{
				border-collapse: collapse;
				tr{
					border: 1px solid #f0f0f0;
					th{
						background-color: #f3f3f3;
						height: 45px;
						&:nth-child(1){
							width: 50px;
							padding-left: 10px;
						}
					}
					td{
						padding-top: 10px;
						padding-bottom: 10px;
						&:nth-child(1){
							text-align: center;
						}
						img{
							width: 80px;
							height: 80px;
							border: 1px solid #eeeeee;
						}
						&:nth-child(3){
							width: 600px;
							padding-left: 20px;
							padding-left: 10px;
							padding-right: 50px;
							&:hover{
								color: #e2231a;
								cursor: pointer;
							}
						}
						&:nth-child(4){
							width: 80px;
							text-align: center;
						}
						&:nth-child(5){
							width: 80px;
							text-align: center;
						}
						&:nth-child(6){
							width: 120px;
							text-align: center;
							font-weight: 700;
						}
						&:nth-child(7){
							width: 80px;
							text-align: center;
						}
					}
				}
			}
			.bottom-tool{
				border: 1px solid #f0f0f0;
				margin-top: 10px;
				height: 50px;
				line-height: 50px;
				.tool-left{
					float: left;
					padding-left: 20px;
					span{
						padd: 0 10px;
						&:hover{
							color: #e2231a;
							cursor: pointer;
						}
					}
					.clear-cart{
						font-size: 14px;
						font-weight: 700;
					}
				}
				.tool-right{
					float: right;
					text-align: right;
					span{
						font-weight: 700;
						color: #acacac;
						em{
							color: #e2231a;
							font-weight: 700;
							padding: 0 5px;
						}
					}
					.price-count{
						em{
							font-size: 16px;	
						}
					}
					.go-order{
						display: inline-block;
						width: 95px;
						height: 50px;
						background-color: #e2231a;
						color: white;
						line-height: 50px;
						text-align: center;
						font-size: 18px;
						font-weight: 700;
					}
				}
			}
		}
	}
</style>